﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace MO.ModelingClient
{
    public partial class DataForm : Form
    {
        public DataForm()
        {
            InitializeComponent();
            DataTable table = DbOperation.DB.ExecuteDataTable("select ED_Code,ED_Name from Entity_Define"); //MySqlHelper.GetDataTable("select * from "+config.TableName);
            foreach (DataRow row in table.Rows)
            {
                TreeNode node = new TreeNode();
                node.Text = row["ED_Name"].ToString();
                node.Tag = row["ED_Code"];
                treeView.Nodes.Add(node);
            }
        }

        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            tableControl1.Enabled = true;
            string tableName = e.Node.Tag.ToString();
            DataConfig config = new DataConfig();
            config.TableName = tableName;
            config.KeyField = tableName + "_CODE";
            config.TitleField = tableName + "_NAME";
            var fields = DataManager.FindFieldByEntityCode(tableName);
            foreach (var field in fields)
            {
                ItemData item = new ItemData(field.Code, field.Name);
                if (field.Type == FieldType.Number)
                {
                    item.Type = DataType.Number;
                }
                else if (field.Type == FieldType.Time)
                {
                    item.Type = DataType.Time;
                }
                else if (field.Type == FieldType.Blob)
                {
                    continue;
                }
                else
                {
                    if (!string.IsNullOrEmpty(field.Reference))
                    {
                        item.Type = DataType.Enum;
                        DataTable table = DbOperation.DB.ExecuteDataTable("select " + field.Reference + "_CODE , " + field.Reference + "_NAME from " + field.Reference);
                        item.Enums = new Dictionary<string, string>();
                        foreach (DataRow row in table.Rows)
                        {
                            item.Enums[row[0].ToString()] = row[1] as string;
                        }
                    }
                }
                config.AddItem(item);
            }
            tableControl1.Init(config);
        }
    }
}
